<template >
  <div class="video-play" @touchstart="start" @touchend="end">
    <!--  暂停icon -->
    <div class="icon-box" @click="startOrPause" v-show='showContent'>
      <div v-show="pauseIcon"><van-icon name="play-circle-o" /></div>
    </div>
    <!-- 横屏状态下 -->
    <div @click="startOrPause" v-if='!showContent'>
      <!-- 返回按钮  -->
      <div class="go-back" @click="goBackScreen">
        <van-icon name="arrow-left" />
      </div>
      <video
        id="videoHeng"
        :src="videoSrc"
        ref="videoAcross"
        loop
        controls
        webkit-playsinline="true" 
        playsinline="true" 
        x5-video-player-fullscreen="true"
        x5-playsinline
        @touchstart="start"
        @touchend="end"
        >您的浏览器不支持 video 标签</video>
    </div>
    <!-- 竖屏状态下 -->
    <div v-if='showContent' @click="startOrPause" class='video-box'>
      <video
        id='video'
        :src="videoSrc"
        loop
        ref="videoVertical"
        @touchstart="start"
        @touchend="end"
        @timeupdate="getCurrentTime"
        webkit-playsinline="true" 
        playsinline="true" 
        x5-video-player-fullscreen="true"
        x5-playsinline
        :poster="content.poster"
        >
        您的浏览器不支持 video 标签
      </video>
        <!-- 以下为插件 -->
    </div>
    <!-- 返回导航 -->
    <div v-show='showContent'>
      <div class="navbar" v-show="showNavbar">
        <van-icon name="arrow-left" @click="goBack"/>
        <img src="../../assets/image/icon_分享.png" alt="" @click='share'>
      </div>
    </div>
    <!-- 点赞，主播信息 -->
    <div class="writerAndRemark" v-show='showContent'>
      <!-- 占位盒子 -->
      <!-- <div class="blank" @click="startOrPause"> -->
        <!-- <div :class="appSourcePosi()" v-show="pauseIcon"><van-icon name="play-circle-o" /></div> -->
      <!-- </div> -->
      <!-- 点赞 -->
      <div class="fun-big-box" :class="isIOSFun">
        <div class="fun-box" >
          <div v-show="!isLike" >
            <img src="../../assets/image/icon／点赞@3x.png" @click="cutOutTime()">
            <span>{{content.likeNum}}</span>
          </div>
          <div v-show="isLike">
            <img src="../../assets/image/icon／已赞@3x.png" @click="cutOutTime()">
            <span>{{content.likeNum}}</span>
          </div>
          <div>
            <img src="../../assets/image/icon／评论@3x.png" @click="funRemark()">
            <span>{{content.remarkNum}}</span>
          </div>
          <div v-show="changeSBut">
            <img src="../../assets/image/icon／切换横屏@3x.png" @click="changeScreen">
          </div>
        </div>
      </div>
      <!-- 作者 -->
      <div class="writer">
        <div class="num-box">{{content.person}}人看过</div>
        <div class="top-box">
          <img class="use-img" :src="content.userImg" alt="" @click="goDetail">
          <div class="user-name">{{content.userName}}</div>
          <img class="user-tag" :src="content.platImg" >
        </div>
        <div class="bottom-box">
          <span>{{content.title}}</span>
          <span class="tags" v-for="(item,index) in content.tags" :key="index">#{{item}}</span>
        </div>
      </div>
      <!-- 评论 -->
      <div class="remark">
        <van-progress
        :percentage="progress"
        stroke-width="1px"
        color="rgba(255, 198, 0, 1)"
        track-color="rgba(255, 255, 255, 1)"
        :show-pivot="false"
        />
        <div class="input-box">
          <form action="javascript:return true">
            <input v-model="value" type="text" placeholder="输入评论内容" @keyup.enter="getInput">
          </form>
        </div>
      </div>
    </div>
    <!-- 展开评论 -->
    <div class="showRemark" v-show='showContent'>
      <van-popup
        v-model="show"
        round position="bottom"
        :style="{ height: '65%' }"
        close-on-click-overlay
        :closeable="true"
        close-icon="arrow-down"
        @close='getVideoData'
      >
      <!-- 评论组件 -->
        <remark-box v-if="show" :id="$route.query.id" :idShow="show"></remark-box>
      </van-popup>
    </div>
    <!-- 分享弹窗 -->
    <div class="share-item" v-show="showShare">
      <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options"
        @select="onSelect"
      />
      <!-- <van-popup v-model="showShare" round position="bottom" :closeable="true">
        <div class="share-title">分享给好友</div>
        <div class="share-item-detail">
          <div class="good-friend">
            <van-icon name="wechat" />
          </div>
          <div class="good-friend">
            <van-icon name="wechat-moments" />
          </div>
        </div>
      </van-popup> -->
    </div>
  </div>
</template>


<script>

import remarkBox from '../../components/common/remarkBox.vue'
import { getVideoMsg, setComment, getLikeVideo, getUserIdData, addFoot} from './api'

export default {
  components: {
    remarkBox
  },
  data() {
    return {
      /* videoSrc: 'https://chezhuapp.oss-cn-beijing.aliyuncs.com/image/20211020/f9240482aa0748519718b8eac37fecd2.mp4',
      content: {
        userImg: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Ftfscom%2Fi3%2F3990335621%2FO1CN01RMWrA91rOSozHBS32_%21%213990335621.jpg_670x670.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637292916&t=3df93c63f9c7b72c58e91208e9b75d36',
        userName: '东哥说车',
        userTags: '懂车帝',
        tags: ['星巢计划','星巢玩车人','星巢评车人'],
        title: '买坦克要等三个月，这车真的不适合年轻？',
        person: 421,
        likeNum: 1212,
        remarkNum: 3344,
        id: ''
      }, */
      // playerOptions: {
      //   sources: [{
      //     src: '',
      //   }],
      //   autoplay: true,
      //   loop: true,
      //   language: 'zh-CN',
      //   notSupportedMessage: '视频加载中，请稍后',
      //   controlBar: false
      // },
      videoSrc: '',
      phoneStatusBarHeight: '',
      content: {
        userImg: '',
        userName: '',
        userTags: '',
        tags: [],
        title: '',
        person: '',
        likeNum: '',
        remarkNum: '',
        id: '',
        remark: '',
        _imageUrl: '',
        platImg: '',
        poster: ''
      },
      isLike: false,
      show: false,
      value: '',
      progress: 0,
      startTouch: '',
      fast: 0,
      videoMsg: {},
      pause: true,
      showContent: true,
      zId: null,
      uId: null,
      changeTime: new Date().getTime(), // 当前时间
      position: 0, // 0为竖，1为横
      isRotate: false,
      showShare: false,
      options: [
        { name: '微信', icon: 'wechat', type: 1 },
        { name: '朋友圈', icon: 'wechat-moments', type: 2 }
      ],
      pauseIcon: false,
      pauseIconIOS: false,
      changeSBut: true,
      loadingMBox: '',
      hasCommit: false,
      autoplay: true,
      showNavbar: true
    }
  },
  methods: {
    // 回退到上一页
    goBack() {
      uni.postMessage({
        data: {
          type: 5
        }
      })
    },
    // 分享
    share() {
      this.showShare = !this.showShare
      // let url = window.location.href
      // uni.postMessage({
      //   data: {
      //     type: 1,
      //     title: this.content.title,
      //     summary: this.content.remark,
      //     _imageUrl: this.content._imageUrl,
      //     shareUrl: url
      //   }
      // })
    },
    // 点击分享
    onSelect(e) {
      console.log(e)
      // 截取掉token
      let url = window.location.href.split('?')
      let url2 = url[1].split('&')

      console.log(url)
      uni.postMessage({
        data: {
          type: e.type,
          title: this.content.title,
          summary: this.content.remark,
          _imageUrl: this.content._imageUrl,
          shareUrl: url[0]+'?'+url2[1],
          share: 1
        }
      })
    },
    // 点击主播头像跳转到主播详情页
    goDetail() {
      this.$router.push({
        name: "hostDetail",
        query: {
          id: this.zId,
        },
      })
    },
    // 获取视频信息
    async getVideoData(n) {
      let id = this.$route.query.id
      console.log(id,this.uId)
      // 请求数据
      const {data} = await getVideoMsg(id, this.uId)
      console.log(this.content)
      // 设置数据
      let tags = data.list[0].tbTagCS.map(item => {
        return item.tagName
      })
      if(data.list[0].state === 0) {
        this.isLike = false
      } else if (data.list[0].state === 1) {
        this.isLike = true
      }
      let detail =  data.list[0].tbVideoManagementCS
      this.videoSrc = detail.videoS
      if(n === 0) {
        this.$nextTick(()=>{
          this.$refs.videoVertical.play()
        })
      }
      // console.log(data.list[0].state)
      this.content.userName = detail.author
      // 处理点赞数
      let good = detail.favour + detail.base
      if(good > 9999) {
        this.content.likeNum = Math.round( good / 10000 ) +'w'
      } else if (good>999) {
        this.content.likeNum = Math.round( good / 1000 ) +'K'
      } else {
        this.content.likeNum = good
      }
      this.content.addLikeNum = detail.favour + detail.base
      this.content.title = detail.videoTitle
      this.content.tags = tags
      this.content.userImg = data.list[0].tbCelebrityManagementCS.images
      this.content.remarkNum = data.list[0].countComment
      this.content.id = detail.id
      this.content.person = data.list[0].countOpen
      this.content.remark = detail.remark
      this.content._imageUrl = detail.cover
      this.content.platImg = data.list[0].platformManagementC.images
      this.content.poster = data.list[0].tbVideoManagementCS.cover !== '' ? data.list[0].tbVideoManagementCS.cover : ''
      this.zId = detail.zId
      this.content.userTags = (data.list[0].platformManagementC === null)? null : data.list[0].platformManagementC.platform
      // this.playerOptions.sources[0].src = this.videoSrc
      // 添加足迹
      const res = await addFoot(detail.id)
      // 如果发表了评论
      if(this.hasCommit) {
        console.log(111)
        this.loadingMBox.clear()
        this.show = !this.show
        this.hasCommit = false
      }

    },
    // 定时器
    cutOutTime() {
      this.changeTime = new Date().getTime()
      setTimeout(() => {
        if(new Date().getTime() - this.changeTime >= 300) {
          this.likeIt()
        }
      }, 300)
    },
    // 点击喜欢，点击取消
    async likeIt() {
      let id = this.content.id
      if(sessionStorage.getItem("token") !== null) {
        this.isLike = !this.isLike
      } else {
        this.$toast({
          message: '请先登录'
        })
      }
      const res = await getLikeVideo(id, this.isLike)
      if(res.code === 40001) {
        this.$toast({
          message: '请先登录'
        })
      } else if (res.code === 0) {
        // console.log(this.isLike)
        // console.log(this.content.likeNum)
        if(this.isLike === true && this.content.addLikeNum/1000<1) {
          this.content.likeNum ++
        } else if (this.isLike === false && this.content.addLikeNum/1000<1) {
          this.content.likeNum --
        }
      } else {
        this.$toast({
          message: '请检查网络'
        })
      }
    },
    funRemark() {
      this.show = true
    },
    // 发表评论
    async comment(comment) {
      this.hasCommit = true
      let params = {
        vid: this.$route.query.id,
        plValue: comment
      }
      const res = await setComment(params)
      if(res.code === 0) {
        this.$toast('评论成功')
        this.value = ''
        this.loadingMBox = this.$toast.loading({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
        });
        this.getVideoData()
        // setTimeout(() => {
        // }, 1500);
      } else if (res.code === 40001) {
        this.$toast('不能发布，请先登录')
      }
    },
    closeMBox() {
      this.getVideoData()
    },
    // 评论不能为空
    getInput() {
      // console.log(this.value)
      if(this.value !== null && this.value !== '') {
        console.log(this.value)
        this.comment(this.value)
      } else {
        this.$toast('评论不能为空')
      }
    },
    // 实时获取视频播放进度
    getCurrentTime() {
      let currentTime, videoLength
      if(this.position === 0) {
        currentTime = this.$refs.videoVertical.currentTime
        videoLength = this.$refs.videoVertical.duration
      } else if (this.position === 1) {
        currentTime = this.$refs.videoAcross.currentTime
        videoLength = this.$refs.videoAcross.duration
      }
      let progress = currentTime / videoLength *100
      this.progress = progress + this.fast
      // console.log(this.progress)
    },
    start(e) {
      this.startTouch = e.changedTouches[0].screenX
      // console.log(this.startTouch)
    },
    end(e) {
      if(this.position === 0) {
        if(this.startTouch < e.changedTouches[0].screenX) {
          this.$refs.videoVertical.currentTime = this.$refs.videoVertical.currentTime + 10
        } else if (this.startTouch > e.changedTouches[0].screenX) {
          this.$refs.videoVertical.currentTime = this.$refs.videoVertical.currentTime - 10
        }
      } else if (this.position === 1) {
        if(this.startTouch < e.changedTouches[0].screenX) {
          this.$refs.videoAcross.currentTime = this.$refs.videoAcross.currentTime + 10
        } else if (this.startTouch > e.changedTouches[0].screenX) {
          this.$refs.videoAcross.currentTime = this.$refs.videoAcross.currentTime - 10
        }
      }
    },
    // 开始或暂停视频
    startOrPause() {
      this.pause = !this.pause
      // console.log(this.pause)
      if(this.pause) {
        // this.$refs.videoAcross.play()
        this.$refs.videoVertical.play()
        this.pauseIcon = false
      } else {
        // this.$refs.videoAcross.pause()
        this.$refs.videoVertical.pause()
        this.pauseIcon = true
      }
    },
    // 监听横竖屏
    screenStatus() {
      let screen = window.orientation
      if (screen === 180 || screen === 0) {
        // console.log('shu')
        this.showContent = true
      } else {
        this.showContent = false
      }
    },
    // 切到横屏
    changeScreen() {
      plus.screen.lockOrientation("landscape-primary")
      this.isRotate = false
      setTimeout(() => {
        this.rotateScreen()
      }, 1000);
    },
    // 判断屏幕旋转有没有成功
    rotateScreen() {
      
    },
    // 返回竖屏
    goBackScreen() {
      // 恢复默认锁屏
      plus.screen.lockOrientation("portrait-primary")
      plus.screen.unlockOrientation()
    },
    // 获取路由链接上拼接的token值
    getTokenInUrl() {
      var url = window.location.href;
      if (url.indexOf("token") > 0) {
        let getTokenParams = window.location.href.split("token=")[1];
        getTokenParams=getTokenParams.split("&")[0];
        if (getTokenParams.length >= 32) {
          getTokenParams = getTokenParams.substr(0, 32);
          sessionStorage.setItem("token", getTokenParams);
        }
      }
    },
    // 获取用户id
    async getUserIdFun() {
      const {data} = await getUserIdData()
      this.uId = data.userId
      this.getVideoData(0)
    },
    // 判断设备是安卓还是ios,设置自动播放
    appSource() {
      const u = navigator.userAgent;
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isiOS) {
        // ios禁止双指缩放, ios禁止，安卓不禁止
        window.addEventListener(
          "touchmove",
          function(event) {
            if (event.scale !== 1) {
            event.preventDefault();
            }
          },
          { passive: false }
        )
        this.pause = false
        this.pauseIcon = true
        this.changeSBut = false
        // this.autoplay = false
        // this.pauseIcon = true
        // 视频一开始就暂停
        // var vdo = document.querySelector('#video')
        // vdo.play(); //视频自动播放
        // vdo.pause(); //视频自动播放
        // document.getElementById('video').play(); //视频自动播放
        // document.getElementById('video').pause(); //视频自动播放
        // this.startOrPause()
      }
    },
    // 判断设备是安卓还是ios，设置播放按钮位置
    appSourcePosi() {
      const u = navigator.userAgent;
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isiOS) {
        return 'pause-icon-IOS'
      }
      return 'pause-icon'
    },
    // 判断设备是安卓还是ios，设置点赞盒子的位置
    isIOSFun() {
      const u = navigator.userAgent;
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isiOS) {
        return 'is-ios'
      }
      return ''
    },
    // 判断是否在微信浏览器打开
    openInWX() {
      var ua = navigator.userAgent.toLowerCase();  
      if(ua.match(/MicroMessenger/i)=="micromessenger") {  
        this.changeSBut = false
        this.showNavbar = false
        this.pause = false
        this.pauseIcon = true
      }
    },
    autoPlayAudio() {
      // var vdo = document.querySelector('#video')
      document.addEventListener('WeixinJSBridgeReady', () => {
        // vdo.play()
         this.$refs.videoVertical.play()
      })
      if (window.navigator.userAgent.match(/MicroMessenger/i) == 'MicroMessenger') {
        WeixinJSBridge.invoke('getNetworkType', {}, function(res) {
          // vdo.play()
           this.$refs.videoVertical.play()
        })
      }
      // vdo.play()
       this.$refs.videoVertical.play()
    },
  },
  mounted() {
    // 实时监听屏幕大小变化
    window.addEventListener("resize", this.screenStatus)
    this.$nextTick(() => {
      // document.getElementById('video').play(); //视频自动播放
      // 解决ios不自动播放的问题
      // this.autoPlayAudio()
      // 判断设备是安卓还是ios
      this.appSource()
    })
    
    
 },
  created() {
    // 获取屏幕状态栏高度
      this.phoneStatusBarHeight = window.phoneStatusBarHeight
    // 修改页面标题
    document.title = "视频播放"
    // 获取路由链接上拼接的token值
    this.getTokenInUrl()
    // 获取视频数据, 判断有无token
    if (sessionStorage.getItem('token') !== null) {
      this.getUserIdFun()
    } else {
      this.getVideoData()
    }
    this.phoneStatusBarHeight = sessionStorage.getItem('phoneStatusBarHeight')
    console.log(sessionStorage.getItem('token'))
    // this.getVideoData()
    // 判断屏幕方向
    this.screenStatus()
    this.openInWX()
    // 用户进入页面播放视频
    // this.pause = true
    /* wx.config({
        // 配置信息, 即使不正确也能使用 wx.ready
        debug: false,
        appId: 'gh_1a8c118653f8',
        timestamp: 1,
        nonceStr: '',
        signature: '',
        jsApiList: []
    });
    wx.ready(function() {
        $("#video")[0].play();
    }); */
  },
  // beforeDestroy() {
  //   // 切换回原来的锁屏
  //   this.goBackScreen()
  //   console.log('销毁前')
  // },
  // destroyed () {
  //   console.log('销毁')
  //   // 恢复默认锁屏
  //   plus.screen.lockOrientation("portrait-primary")
  //   plus.screen.unlockOrientation()
  // }
}
</script>

<style scoped lang="less">
.icon-box{
  // background-color: pink;
  width: 100%;
  height: 15vh;
  position: absolute;
  top: 42%;
  text-align: center;
  line-height: 15vh;
  font-size: 70px;
  color: white;
  // z-index: 200;
}
.pause-icon{
  // text-align: center;
  position: absolute;
  top: -25%;
  left: 40%;
  font-size: 100px;
  color: rgb(255, 255, 255)
}
.pause-icon-IOS{
  // text-align: center;
  position: absolute;
  top: -50%;
  left: 40%;
  font-size: 100px;
  color: rgb(255, 255, 255)
}
.share-item{
  .van-popup{
    height: 200px;
    .share-title{
      margin-top: 30px;
      text-align: center;
    }
    .share-item-detail{
      display: flex;
      div{
        flex: 1;
        text-align: center;
      }
    }
  }
}
.rotate-box{
  transform: rotate(90deg);
}
.video-play{
  position: absolute; // 改为absolute在ios可以固定
  // top: env(safe-area-inset-bottom);
  background-color: black;
  height: 100vh; // 100vh可以覆盖整个屏幕
  width: 100%;
  overflow: hidden;
  // padding-bottom: env(safe-area-inset-bottom);
  // margin-top: constant(safe-area-inset-top);
  .go-back{
    color: white;
    position: absolute;
    top: 0;
    z-index: 101;
    margin-left: 16px;
    margin-top: 15px;
    font-size: 12px;
  }
  .navbar{
    position: absolute;
    top: 0;
    color: white;
    font-size: 20px;
    width: calc(~'100% - 40px');
    display: flex;
    justify-content: space-between;
    padding: 58px 20px 0 20px;
    z-index: 9;
    img{
      width: 20px;
      height: 20px;
    }
  }
  .writerAndRemark{
    position: absolute;
    bottom: 0;
    width: calc(~'100% - 32px');
    padding: 0 16px 46px 16px;
    .blank{
      position: absolute;
      bottom: 50%;
      width: calc(~'100% - 70px');
      height: 50%;
    }
    .is-ios{
      top: calc(~'-120px - 37px') !important;
    }
    .fun-big-box{
      position: absolute;
      top: -120%;
      right: 5%;
      .fun-box{
        display: flex;
        flex-flow: column;
        align-items: flex-end;
        text-align: right;
        div{
          padding: 10px 0;
        }
        img{
          height: 34px;
          width: 34px;
        }
        span{
          text-align: center;
          display: block;
          font-size: 14px;
          font-family: PingFangHK-Medium, PingFangHK;
          font-weight: 500;
          color: #FFFFFF;
        }
      }
    }
    .writer{
      color: white;
      .num-box{
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
      }
      .top-box{
        display: flex;
        align-items: center;
        padding: 17px 0 8px 0;
        .use-img{
          height: 36px;
          width: 36px;
          border-radius: 50%;
        }
        .user-name{
          padding: 0 9px;
          font-size: 16px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
        }
        .user-tag{
          background-color: rgba(255, 198, 0, 1);
          border-radius: 2px;
          font-size: 12px;
          padding: 2px;
          color: black;
        }
        .user-tag{
          width: 40px;
          height: 15px;
        }
      }
      .bottom-box{
        padding-bottom: 14px;
        .tags{
          color: rgba(246, 196, 1, 1);
        }
      }
    }
    .remark{
      .input-box{
        height: 34px;
        width: 100%;
        color: white;
        padding-top: 12px;
        input{
          height: 34px;
          width: calc(~'100% - 16px');
          padding-left: 16px;
          background-color: rgba(255, 255, 255, .3);
          border: none;
          border-radius: 17px;
        }
        input::-webkit-input-placeholder{
          color: white;
          font-size: 15px;
          font-weight: 400;
        }
      }
    }
  }

}
  video{
    width: 100%;
    height: 100vh;
  }
</style>
